import 'package:flutter/material.dart';
import '../widgets/platform/adaptive_card.dart';
import '../../core/platform/platform_detector.dart';

/// 高级搜索组件
class AdvancedSearch extends StatefulWidget {
  final ValueChanged<SearchFilters>? onSearch;
  final VoidCallback? onReset;

  const AdvancedSearch({
    super.key,
    this.onSearch,
    this.onReset,
  });

  @override
  State<AdvancedSearch> createState() => _AdvancedSearchState();
}

class _AdvancedSearchState extends State<AdvancedSearch> {
  bool _isExpanded = false;
  final TextEditingController _searchController = TextEditingController();
  String _requester = '';
  String _businessDomain = '';
  String _status = '全部';
  DateTime? _startDate;
  DateTime? _endDate;

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SelectableText(
                '需求筛选',
                style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
              ),
              TextButton(
                onPressed: () {
                  setState(() {
                    _isExpanded = !_isExpanded;
                  });
                },
                child: SelectableText(_isExpanded ? '收起筛选器' : '展开筛选器'),
              ),
            ],
          ),
          const SizedBox(height: 16),
          // 搜索框
          TextField(
            controller: _searchController,
            decoration: InputDecoration(
              hintText: '搜索需求、提需人、组织...',
              prefixIcon: const Icon(Icons.search),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              contentPadding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 12,
              ),
            ),
          ),
          const SizedBox(height: 16),
          // 高级筛选器
          if (_isExpanded) ...[
            _buildAdvancedFilters(),
            const SizedBox(height: 16),
          ],
          // 操作按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  ElevatedButton(
                    onPressed: _handleSearch,
                    child: const SelectableText('应用筛选'),
                  ),
                  const SizedBox(width: 8),
                  OutlinedButton(
                    onPressed: _handleReset,
                    child: const SelectableText('重置'),
                  ),
                ],
              ),
              Row(
                children: [
                  const SelectableText('排序方式'),
                  const SizedBox(width: 8),
                  DropdownButton<String>(
                    value: '创建时间',
                    items: const [
                      DropdownMenuItem(
                        value: '创建时间',
                        child: SelectableText('创建时间'),
                      ),
                      DropdownMenuItem(
                        value: '更新时间',
                        child: SelectableText('更新时间'),
                      ),
                      DropdownMenuItem(
                        value: '优先级',
                        child: SelectableText('优先级'),
                      ),
                    ],
                    onChanged: (value) {
                      // 处理排序方式变化
                    },
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建高级筛选器
  Widget _buildAdvancedFilters() {
    return Column(
      children: [
        if (PlatformDetector.isDesktop() || PlatformDetector.isWeb())
          GridView.count(
            crossAxisCount: 4,
            crossAxisSpacing: 16,
            mainAxisSpacing: 16,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: [
              _buildTextFieldFilter('提需人 / 组织', _requester, (value) {
                setState(() {
                  _requester = value;
                });
              }),
              _buildTextFieldFilter('业务域', _businessDomain, (value) {
                setState(() {
                  _businessDomain = value;
                });
              }),
              _buildDropdownFilter(
                  '当前状态', _status, const ['全部', '待处理', '进行中', '已完成', '异常'],
                  (value) {
                if (value != null) {
                  setState(() {
                    _status = value;
                  });
                }
              }),
              _buildDateRangeFilter(),
            ],
          )
        else
          Column(
            children: [
              _buildTextFieldFilter('提需人 / 组织', _requester, (value) {
                setState(() {
                  _requester = value;
                });
              }),
              const SizedBox(height: 16),
              _buildTextFieldFilter('业务域', _businessDomain, (value) {
                setState(() {
                  _businessDomain = value;
                });
              }),
              const SizedBox(height: 16),
              _buildDropdownFilter(
                  '当前状态', _status, const ['全部', '待处理', '进行中', '已完成', '异常'],
                  (value) {
                if (value != null) {
                  setState(() {
                    _status = value;
                  });
                }
              }),
              const SizedBox(height: 16),
              _buildDateRangeFilter(),
            ],
          ),
      ],
    );
  }

  /// 构建文本输入筛选器
  Widget _buildTextFieldFilter(
    String label,
    String value,
    ValueChanged<String> onChanged,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SelectableText(
          label,
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 4),
        TextField(
          decoration: InputDecoration(
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 8,
              vertical: 8,
            ),
            isDense: true,
          ),
          style: const TextStyle(fontSize: 12),
          onChanged: onChanged,
        ),
      ],
    );
  }

  /// 构建下拉筛选器
  Widget _buildDropdownFilter(
    String label,
    String value,
    List<String> items,
    ValueChanged<String?> onChanged,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SelectableText(
          label,
          style: const TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 4),
        DropdownButtonFormField<String>(
          initialValue: value,
          items: items
              .map((item) => DropdownMenuItem(
                    value: item,
                    child: SelectableText(
                      item,
                      style: const TextStyle(fontSize: 12),
                    ),
                  ))
              .toList(),
          onChanged: onChanged,
          decoration: InputDecoration(
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 8,
              vertical: 8,
            ),
            isDense: true,
          ),
          style: const TextStyle(fontSize: 12),
        ),
      ],
    );
  }

  /// 构建日期范围筛选器
  Widget _buildDateRangeFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SelectableText(
          '创建时间',
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 4),
        Row(
          children: [
            Expanded(
              child: TextField(
                readOnly: true,
                decoration: InputDecoration(
                  hintText: '开始日期',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(4),
                  ),
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 8,
                  ),
                  isDense: true,
                  suffixIcon: const Icon(Icons.calendar_today, size: 16),
                ),
                style: const TextStyle(fontSize: 12),
                onTap: () async {
                  final date = await showDatePicker(
                    context: context,
                    initialDate: DateTime.now(),
                    firstDate: DateTime(2020),
                    lastDate: DateTime(2030),
                  );
                  if (date != null) {
                    setState(() {
                      _startDate = date;
                    });
                  }
                },
              ),
            ),
            const SizedBox(width: 8),
            const SelectableText('-'),
            const SizedBox(width: 8),
            Expanded(
              child: TextField(
                readOnly: true,
                decoration: InputDecoration(
                  hintText: '结束日期',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(4),
                  ),
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 8,
                  ),
                  isDense: true,
                  suffixIcon: const Icon(Icons.calendar_today, size: 16),
                ),
                style: const TextStyle(fontSize: 12),
                onTap: () async {
                  final date = await showDatePicker(
                    context: context,
                    initialDate: DateTime.now(),
                    firstDate: DateTime(2020),
                    lastDate: DateTime(2030),
                  );
                  if (date != null) {
                    setState(() {
                      _endDate = date;
                    });
                  }
                },
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 处理搜索
  void _handleSearch() {
    final filters = SearchFilters(
      searchQuery: _searchController.text,
      requester: _requester,
      businessDomain: _businessDomain,
      status: _status,
      startDate: _startDate,
      endDate: _endDate,
    );

    widget.onSearch?.call(filters);
  }

  /// 处理重置
  void _handleReset() {
    setState(() {
      _searchController.clear();
      _requester = '';
      _businessDomain = '';
      _status = '全部';
      _startDate = null;
      _endDate = null;
    });

    widget.onReset?.call();
  }
}

/// 搜索过滤器数据模型
class SearchFilters {
  final String searchQuery;
  final String requester;
  final String businessDomain;
  final String status;
  final DateTime? startDate;
  final DateTime? endDate;

  SearchFilters({
    required this.searchQuery,
    required this.requester,
    required this.businessDomain,
    required this.status,
    required this.startDate,
    required this.endDate,
  });
}
